import { EventSourcePolyfill } from 'event-source-polyfill';
interface EventSubscribeInfo {
  callback: (value: any) => any | undefined,
  origin: string
}

/**
 * 事件组件
 */
class EventComponent {
  private eventSourceDomain = '/MessageCenter/Subscribe'
  private Events: Record<string, EventSubscribeInfo[]>
  public Instance: EventSource

  constructor() {
    this.Events = {};
    this.Instance = this.createInstance();
  }

  /**
   * 创建实例
   */
  private createInstance() {
    // 权鉴头信息
    const accessToken = localStorage.getItem("access-token") || '',
      refreshToken = localStorage.getItem("x-access-token");
    const authHeader = { Authorization: `Bearer ${accessToken}`,"Cache-Control":"no-cache" };
    if (refreshToken) {
      authHeader["X-Authorization"] = `Bearer ${refreshToken}`;
    }

    // 创建EventSource实例
    const source = new EventSourcePolyfill(this.eventSourceDomain, {
      headers: authHeader
    });

    /* 创建常规监听事件 */
    source.addEventListener('Heartbeat', (e: any) => {
      const datainstance = JSON.parse(e.data);
      console.info(`%c心跳检测`, 'color: #409EFF;', datainstance);
    })

    source.addEventListener('open', function () {
      // Connection was opened.
      console.info(`%c事件源连接已打开.`, 'color: #67C23A;');
    }, false);

    source.addEventListener('error', function (e: any) {
      if (e.readyState == EventSource.CLOSED) {
        // Connection was closed.
        console.error(`%c事件源连接已关闭.`, 'color: #F56C6C;');
      }
      else {
        console.error(e, source);
      }
    }, false);
    
    return source;
  }




  public on(eventName: string, handleCallback: (value: any) => any) {
    let eventQueue = this.Events[eventName];
    const origin = window.location.pathname;
    console.info('EventComponent.subscribe.parmas', eventName, origin);

    const handlerMessage = ({ data }: any) => {
      const datainstance = JSON.parse(data);
      console.log(`%c收到消息`, 'color: #409EFF;', datainstance);
      // 在队列中查找
      const eventTypes = this.Events[eventName] || [];
      if (eventTypes.length) {
        const info = eventTypes.find(x => x.origin == origin);
        info?.callback(datainstance);
      }
    }

    if (eventQueue) {
      const subscribeInfo = eventQueue.find(x => x.origin == origin);
      if (subscribeInfo) {
        subscribeInfo.callback = handleCallback;
      }
      else {
        eventQueue = [...eventQueue, {
          origin,
          callback: handleCallback,
        }]
      }
    }
    else {
      // 添加事件监听
      this.Instance.addEventListener(eventName, (e: any) => {
        handlerMessage(e);
      });

      eventQueue = [
        {
          origin,
          callback: handleCallback,
        }
      ]
    }

    // 更新整个队列
    this.Events[eventName] = eventQueue;
  }

}

export default EventComponent;
